<template>
  <div>
    <el-card>
      <!-- class="project-list-container" -->
      <div>
        <div class="list-h">
          <el-button
            v-auth="`/system/information-add`"
            type="primary"
            @click="handleAdd"
            class="add-option"
            >新增</el-button
          >
          <el-form
            :inline="true"
            class="demo-form-inline"
            :model="formInline"
            ref="formRef"
            @submit.prevent
          >
            <el-form-item label="标题内容" prop="titleLike">
              <el-input
                v-model.trim="formInline.titleLike"
                clearable
                class="width-custom120"
              ></el-input>
            </el-form-item>
            <el-form-item label="创建人" prop="createUserNameLike">
              <el-input
                v-model.trim="formInline.createUserNameLike"
                clearable
                class="width-custom120"
              ></el-input>
            </el-form-item>
            <el-form-item label="创建时间" prop="">
              <el-date-picker
                clearable
                class="width-custom220"
                v-model="timeValue"
                type="daterange"
                range-separator="-"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                value-format="YYYY-MM-DD"
                @change="handleChangeDate"
              />
            </el-form-item>
            <el-form-item label="发布时间" prop="">
              <el-date-picker
                clearable
                class="width-custom220"
                v-model="timeValue2"
                type="daterange"
                range-separator="-"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                value-format="YYYY-MM-DD"
                @change="handleChangeDate2"
              />
            </el-form-item>
            <el-form-item label="状态" prop="companyNameLike">
              <el-select
                v-model="formInline.publishType"
                class="width-custom120"
                clearable
              >
                <el-option
                  v-for="item in InfoStatusList"
                  :label="item.value"
                  :key="item.key"
                  :value="item.key"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="信息类型" prop="infoType">
              <el-select
                v-model="formInline.infoType"
                class="width-custom120"
                clearable
              >
                <el-option label="公告" key="1" value="1"></el-option>
                <el-option label="资讯" key="2" value="2"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button @click="handleReset">重置</el-button>
              <el-button type="primary" @click="handleSearch">查询</el-button>
            </el-form-item>
          </el-form>
        </div>

        <el-skeleton style="height: 50vh" :rows="8" :loading="loading" animated>
          <el-table
            :data="state.tableData"
            border
            style="width: 100%"
            v-loading="loading"
            :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
          >
            <template #empty>
              <el-empty :image-size="150" description="暂无数据"></el-empty>
            </template>
            <el-table-column
              type="index"
              label="序号"
              width="60"
            ></el-table-column>

            <el-table-column
              prop="infoNum"
              label="信息编码"
              width="140"
            ></el-table-column>
            <el-table-column
              prop="summary"
              label="信息摘要"
              show-overflow-tooltip
              :min-width="120"
            ></el-table-column>
            <el-table-column
              prop="title"
              label="标题内容"
              :min-width="120"
            ></el-table-column>
            <!-- <el-table-column prop="" label="图片">
              <template #default="{ row }">
                <img
                  :src="initPrview(row.coverImg)"
                  v-if="row.coverImg"
                  class="tableSrc"
                />
              </template>
            </el-table-column> -->
            <!-- <el-table-column prop="sortNum" label="排序"></el-table-column> -->
            <el-table-column
              prop="createUserName"
              label="创建人"
              width="100"
            ></el-table-column>

            <el-table-column
              prop="createTime"
              label="创建时间"
              width="140"
            ></el-table-column>
            <el-table-column
              prop="publishTime"
              label="发布时间"
              width="140"
            ></el-table-column>
            <!-- <el-table-column prop="offtime" label="停用时间"></el-table-column> -->
            <el-table-column prop="" label="状态" width="80">
              <template #default="{ row }">
                {{ formatterStatusType(row) }}
              </template>
            </el-table-column>
            <el-table-column prop="title" label="信息类型" width="80">
              <template #default="{ row }">
                {{ formatterType(row) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="160" fixed="right">
              <template #default="{ row }">
                <el-button
                  v-auth="`/system/information-look`"
                  type="text"
                  @click="handleEdit(row, 'look')"
                  >查看</el-button
                >
                <el-button
                  v-auth="`/system/information-edit`"
                  type="text"
                  @click="handleEdit(row)"
                  >编辑</el-button
                >

                <template v-if="row.publishType !== '1'">
                  <el-button
                    v-auth="`/system/information-publish`"
                    type="text"
                    @click="handlePublish(row)"
                    >发布</el-button
                  >
                </template>
                <template v-else>
                  <el-button
                    v-auth="`/system/information-publish`"
                    type="text"
                    @click="handleUnPublish(row)"
                    >撤回</el-button
                  >
                </template>
                <el-popconfirm
                  confirm-button-text="确定"
                  cancel-button-text="取消"
                  icon="el-icon-info"
                  icon-color="red"
                  title="确定删除该条记录吗？"
                  @confirm="handleDelete(row)"
                >
                  <template #reference>
                    <el-button v-auth="`/system/information-del`" type="text"
                      >删除</el-button
                    >
                  </template>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </el-skeleton>
      </div>
      <re-pagination
        :total="total"
        v-show="total > 0"
        v-model:page="formInline.pageNum"
        v-model:limit="formInline.pageSize"
        @pagination="handleSearch"
      />
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";
import {
  postInfoManageList,
  postInfoManageDelete,
  postInfoPublish,
  postInfoUnPublish
} from "/@/api/information";
import NotifMessage from "/@/utils/message/notification";
import { useRouter } from "vue-router";
// import RePagination from "/@/components/RePagination/index.vue";

import { InfoStatusMap, infoManageType, InfoStatusList } from "./types";
// import { storageLocal } from "/@/utils/storage";

let timeValue = ref(null);
let timeValue2 = ref(null);

const router = useRouter();

const formRef = ref<HTMLFormElement | null>(null) as any;

let loading = ref<boolean>(false);

let total = ref<number>(0);

let formInline = reactive<any>({
  titleLike: "",
  createUserNameLike: "",
  createTimeStrStart: "",
  createTimeStrEnd: "",
  publishTimeStrStart: "",
  publishTimeStrEnd: "",
  publishType: "",
  pageSize: 10,
  pageNum: 1,
  infoType: null
});
// let mode = ref<string>("add");
let state = reactive({
  tableData: [],
  companyInfo: {}
});

// 请求公司列表表格数据
async function getTableData(obj: object = {}) {
  // 真实请求待添加
  loading.value = true;
  try {
    const { code, data } = await postInfoManageList(obj);
    if (code === 200) {
      state.tableData = data.list;
      total.value = data.rows;
    }
  } catch (err) {
    console.log(err);
  } finally {
    loading.value = false;
  }
}
// 打开添加人员弹窗
const handleAdd = (): void => {
  router.push({ path: "/system/information/detail", query: { mode: "add" } });
};

// 操作
// const onEmitSubmit = (isSubmit: boolean) => {
//   dialogFormVisible.value = false;
//   if (isSubmit) {
//     getTableData();
//   }
// };

// 清除表单，重置
const handleReset = () => {
  formRef.value.resetFields();
  handleChangeDate(null);
  handleChangeDate2(null);
};

const handleChangeDate = item => {
  console.log(item, "date");
  timeValue.value = item;
  if (item) {
    formInline.createTimeStrStart = item[0];
    formInline.createTimeStrEnd = item[1];
  } else {
    formInline.createTimeStrStart = "";
    formInline.createTimeStrEnd = "";
  }
};
const handleChangeDate2 = item => {
  console.log(item, "date");
  timeValue2.value = item;
  if (item) {
    formInline.publishTimeStrStart = item[0];
    formInline.publishTimeStrEnd = item[1];
  } else {
    formInline.publishTimeStrStart = "";
    formInline.publishTimeStrEnd = "";
  }
};

// 根据条件进行搜索
const handleSearch = (): void => {
  getTableData(formInline);
};

// 删除记录
const handleDelete = async item => {
  try {
    const { code, message } = await postInfoManageDelete({ id: item.id });
    if (code === 200) {
      NotifMessage.success(`${message}`);
      getTableData();
    } else {
      NotifMessage.error(`${message}`);
    }
  } catch (err) {
    console.log(err);
  }
  // const rdmsInfo = storageLocal.getItem("rdms-info");
  // if (item.publishType !== 1 && rdmsInfo.name === item.createUserName) {
  //   NotifMessage.warning(`当前状态无法删除！`);
  // } else {
  //   try {
  //     const { code, message } = await postInfoManageDelete({ id: item.id });
  //     if (code === 200) {
  //       NotifMessage.success(`${message}`);
  //       getTableData();
  //     } else {
  //       NotifMessage.error(`${message}`);
  //     }
  //   } catch (err) {
  //     console.log(err);
  //   }
  // }
};

const handleEdit = (row, type = "edit") => {
  router.push({
    path: "/system/information/detail",
    query: { id: row.id, mode: type }
  });
  // const rdmsInfo = storageLocal.getItem("rdms-info");
  // if (row.publishType !== 1 && rdmsInfo.name === row.createUserName) {
  //   NotifMessage.warning(`当前状态无法编辑！`);
  // } else {
  //   router.push({
  //     path: "/system/information/detail",
  //     query: { id: row.id, mode: type }
  //   });
  // }
};

const handlePublish = async row => {
  try {
    const { code, message } = await postInfoPublish({ id: row.id });
    if (code === 200) {
      NotifMessage.success(`${message}`);
      getTableData();
    } else {
      NotifMessage.error(`${message}`);
    }
  } catch (err) {
    console.log(err);
  }
};

const handleUnPublish = async row => {
  try {
    const { code, message } = await postInfoUnPublish({ id: row.id });
    if (code === 200) {
      NotifMessage.success(`${message}`);
      getTableData();
    } else {
      NotifMessage.error(`${message}`);
    }
  } catch (err) {
    console.log(err);
  }
};

const formatterStatusType = row => {
  if (!row.publishType) return "-";
  return InfoStatusMap.get(row.publishType);
};

const formatterType = row => {
  if (!row.infoType) return "-";
  if (infoManageType[row.infoType - 1]) {
    return infoManageType[row.infoType - 1].key;
  }
  return "-";
};

// const initPrview = item => {
//   if (!item) return;
//   const imgStr = JSON.parse(item);
//   return imgStr.url;
// };

// 请求数据
getTableData(formInline);
</script>

<style lang="scss" scoped>
.tableSrc {
  width: 100px;
}
</style>
